﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
public partial class Common_BooksDetail : System.Web.UI.Page
{
    public string navstring;
    public static string userName = "登陆";
    public string indexImages;
    public string myControl1;
    public string myControl2;
    public string myControl3;
    public string myControl4;
    protected int NumbersOfImages = 0;
    public string temp = "<code style=\"font-family:FZBeiWeiKaiShu-S19S;color:red;font-size:100%\">(您还未登陆)</code>";
    public string para, data, place, atc, content, imageplace, bookname, publishCompany, write, bookT;//bookT是ID
    public string ERCODE = "";
    protected int justnowBooksNum = 0;
    public static string bookid2 = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        
        //if (!IsPostBack)
        //{


            if (Session["userName"] == null)
            {
                navstring = "<a id=\"myid1\" style=\"width: 84px;color:#fff;\" href=\"#\" data-toggle=\"modal\" data-target=\"#myModal\"><span  class=\"glyphicon glyphicon-log-in\"></span> 登录";
                sureborrowe.Enabled = false;
            }
            else
            {
                navstring = " <a id=\"myid1\" href=\"../User/UserIndexInfo.aspx?userName=" + Session["userName"].ToString() + "\" style=\"width: 84px;color:#fff;\" ><span  class=\"glyphicon glyphicon-user\"></span>" + Session["userName"].ToString();
                temp = "<code style=\"font-family:FZBeiWeiKaiShu-S19S;color:#41B300;font-size:100%\">" + Session["userName"] + "</code>";
                sureborrowe.Enabled = true;
            }  
        //}
        para = Request.QueryString["BookID"];
        bookid2 = para;//biaoji
        if (para!=null)
        {
            SQL sql = new SQL();
            DataSet ds = sql.getDataset("select * from book_info,Book_status,Book_type,Publish_company where Book_info.StatusID=Book_status.StatusID and  book_info.PublishCompanyID=Publish_company.PublishCompanyID and Book_info.BookType=Book_Type.BookType and  BookID='" + para + "'", para);
            DataTable dt = new DataTable();
            DataRow drow;
            DataRowCollection drc;
            dt = ds.Tables[0];
            drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                drow = drc[i];
                bookT = drow[0].ToString();
                bookname = drow[1].ToString();
                string atr=drow[2].ToString();
                write = drow[3].ToString();

                string price = drow[5].ToString();

                string publishdate = drow[7].ToString();
                publishdate = string.Format("{0:yyyy-MM-dd}", DateTime.Parse(publishdate));
                string nownum = drow[9].ToString();
                string amount = drow[8].ToString();

                string indate = string.Format("{0:yyyy-MM-dd}", DateTime.Parse(drow[11].ToString()));
                string isbn = drow[12].ToString();
                string beborrow = drow[15].ToString();
                string bookplace = drow[16].ToString();
                string findbooknum = drow[17].ToString();
                string imageURL = drow[18].ToString();
                string mulu = drow[19].ToString();
                string status = drow[21].ToString();
                string bookTypename = drow[23].ToString();
                publishCompany = drow[25].ToString();

                data += "<tbody><tr><td>图书编号：</td><td>" + bookT + "</td></tr><tr><td>图书名称：</td><td>" + bookname + "</td></tr><tr><td>作者：</td><td>" + write + "</td></tr><tr><td>出版社：</td><td>" + publishCompany + "</td></tr><tr><td>出版时间：</td><td>" + publishdate + "</td></tr> <tr><td>图书收录时间：</td><td>" + indate + "</td></tr> <tr><td>ISBN：</td><td>" + isbn + "</td></tr><tr><td>分类:</td><td>" + bookTypename + "</td></tr><tr><td>索书号：</td><td>" + findbooknum + "</td></tr><tr><td>价格：</td><td>" + price + "</td></tr></tr><tr><td>图书状态：</td><td>" + status + "</td></tr><tr><td>图书总数：</td><td>" + amount + "</td></tr><tr><td>在馆数：</td><td>" + nownum + "</td></tr><tr><td>累借次数：</td><td>" + beborrow + "</td></tr><tr><td>累借天数：</td><td>" + beborrow + "</td></tr></tbody>";
                place = "<td>" + bookname + "</td><td>" + findbooknum + "</td><td>" + bookplace + "</td>";
                atc = atr;
                content=mulu;
                imageplace = "<a href=\""+imageURL+"\"><img src=\"" + imageURL + "\" style=\"width:100%\" alt=\"" + bookname + "\"></a>";
            }


            if (Request.QueryString["BookID"] != null)
            {
                
                ERCODE = "http://liantu.api.juhe.cn/api.php?text=http://kexieweb.guet.edu.cn/BookManage/Common/ERcodeLendBooks.aspx?BookId=" + Request.QueryString["BookID"].ToString() + "&bg=&fg=&gc=&el=&w=&m=&pt=&inpt=&logo=&key=8d3aa899427d9043dafc96e6006f9d99";
            }
            //检测书籍是否被借阅，弹窗
            // WaittingLend wt = new WaittingLend();

             //if (wt.reflashResult(Request.QueryString["BookID"].ToString(),justnowBooksNum))
             //{
             //    Response.Write("<script language=javascript>alert('您已成功扫码借阅本书');window.location = 'BMindex.aspx';</script>");
             //}


            /*采用多线程检测书本是否已经被借阅
            ThreadStart threadStart = new ThreadStart(delegate()
            {
                SQL sql2 = new SQL();
                while (true)
                {
                    justnowBooksNum = Convert.ToInt32(sql.EXQSQL("select COUNT(*) from Borrow_books_manage where BookID='" + bookid2 + "'"));
                    if (Convert.ToInt32(sql2.EXQSQL("select COUNT(*) from Borrow_books_manage where BookID='" + bookid2 + "'")) > justnowBooksNum)
                    {
                        Response.Write("<script language=javascript>alert('您已成功扫码借阅本书');window.location = 'BMindex.aspx';</script>");
                        return;
                    }
                    else
                    {
                       
                        Thread.Sleep(1000);
                    }
                }

            });
            Thread thread = new Thread(threadStart);
            thread.Start();//多线程启动匿名方法*/


        }





    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string bookName = "";
        string url = "";
        bookName = TBFindBook.Value.ToString();
        url = "FindBook.aspx?bookName=" + bookName;
        Response.Redirect(url);
    }
    protected void UserLogin(object sender, EventArgs e)
    {
        userName = TBuserName.Text;
        navstring = "<a href=\"../User/UserIndex.aspx\"><span  class=\"glyphicon glyphicon-user\"></span>   " + userName;
    }
    protected void sureborrowe_Click(object sender, EventArgs e)
    {
        SQL sql = new SQL();
        string psw = sql.getDataFormTable("password", "reader_info", "readerID", Session["userName"].ToString(), "", "", "", "", 1);
        int booknum = Convert.ToInt32(sql.getDataFormTable("CURRENTNUM", "book_info", "bookID", bookT, "", "", "", "", 1));
        int BeborrowTimes = Convert.ToInt32(sql.getDataFormTable("BeBorrowTimes", "book_info", "bookID", bookT, "", "", "", "", 1));
        //执行步骤：
        //1、检查用户是否登陆
        //2、检查密码是否正确
        //3、检查图书是否在库
       
        //4、检查图书剩余数量
        //5、借阅单号写入借阅单表
        //6\检查是否超过自己读者类型的最大限制本数量
        /*修正：增加一个对自己账户余额的检测*/
        //6、图书信息表修改目前图书数量，图书状态，图书被借次数
        if (psw.Equals(TextBox1.Text))
        {
            string status = sql.getDataFormTable("statusID", "book_info", "bookID", bookT, "", "", "", "", 1);
            if (status.Equals("1"))
            {
                int kejieyuetushu = 0;
                string typeid = sql.getDataFormTable("ReaderType", "Reader_info", "readerid", Session["userName"].ToString(), "", "", "", "", 1);
                kejieyuetushu = Convert.ToInt32(sql.EXQSQL("select maxlend from reader_type where readertype=" + typeid + ""));
                if (Convert.ToInt32(sql.EXQSQL("select count(*) from Borrow_books_manage where readerID='" + Session["userName"].ToString() + "' and returndate is null ")) <= kejieyuetushu)
                {
                    if (Convert.ToDouble(sql.EXQSQL("select LOWERLIMIT FROM System_state WHERE INFOID=1")) < Convert.ToDouble(sql.EXQSQL("select account from Reader_info where readerid='"+Session["userName"].ToString()+"'")))
                    {
                            if (Convert.ToInt32(sql.getDataFormTable("CURRENTNUM", "book_info", "bookID", bookT, "", "", "", "", 1)) > 0)
                        {
                            string shouldReturnday = DateTime.Now.AddDays(Convert.ToInt32(sql.EXQSQL("select Borrowdays from System_state"))).ToString();
                            sql.updateBOOKinfo("insert into Borrow_books_manage(BookID,ReaderID,DDNUM,LendBookDate,ShouldReturnDate,XUJIETIMES) values('" + bookT + "','" + Session["userName"].ToString() + "','" + bookT + Session["userName"].ToString() + string.Format("{0:yyyymmddhhmmss}", DateTime.Now) + "','" + DateTime.Now.ToString() + "','" + shouldReturnday + "','0')");//写入借阅单表

                            sql.EXQSQL("update Book_info set CurrentNum=" + (booknum - 1) + ",statusid=2,BeBorrowTimes=" + (BeborrowTimes + 1) + " where bookid=" + bookT + "");
                            Response.Write("<script language=javascript>alert('完成借阅');</script>");
                        }
                        else
                        {
                            Response.Write("<script language=javascript>alert('图书已经全部借出');</script>");
                        }
                    } 
                    else
                    {
                        Response.Write("<script language=javascript>alert('您的账户余额不足');</script>");
                    }
                    
                }
                else
                {
                    Response.Write("<script language=javascript>alert('您已经超过最大可借数量');</script>");

                }

            }
            else
            {
                Response.Write("<script language=javascript>alert('图书不在库');</script>");
            }
        }
        else
        {
            Response.Write("<script language=javascript>alert('您的密码不正确，请重新输入');</script>");
        }
    }

    protected void getQRCode(object sender, EventArgs e)
    {
        if (Request.QueryString["BookID"] != null)
        {
            ERCODE = "http://liantu.api.juhe.cn/api.php?text=http://kexieweb.guet.edu.cn/BookManage/Common/ERcodeLendBooks.aspx?BookId=" + Request.QueryString["BookID"].ToString() + "&bg=&fg=&gc=&el=&w=&m=&pt=&inpt=&logo=&key=8d3aa899427d9043dafc96e6006f9d99";
        }
    }
}